package com.linkage.jz.bankruptcy.activity.Project.ZQUser;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.linkage.jz.bankruptcy.R;
import com.linkage.jz.bankruptcy.adapter.FullyGridLayoutManager;
import com.linkage.jz.bankruptcy.base.BaseCreateActivity;
import com.linkage.jz.bankruptcy.bean.ObjValInfo;
import com.linkage.jz.bankruptcy.bean.SerializedZQApplyFileList;
import com.linkage.jz.bankruptcy.bean.TaskAtta;
import com.linkage.jz.bankruptcy.bean.ZQBaseProjectCrDecInfo;
import com.linkage.jz.bankruptcy.net.BaseResponse;
import com.linkage.jz.bankruptcy.net.BaseSubscriber;
import com.linkage.jz.bankruptcy.net.Network;
import com.linkage.jz.bankruptcy.utils.SelectPicHelpler;
import com.linkage.jz.bankruptcy.utils.UploadImageConverter;
import com.linkage.seapeak.activity.project.ExamineAdvActivity;
import com.linkage.seapeak.pojo.UploadImage;
import com.linkage.seapeak.view.QuickPopView;

import org.json.JSONArray;
import org.json.JSONObject;

import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

import static com.linkage.jz.bankruptcy.activity.Project.ZQUser.CreateZQFristApplyActivity.KEY_CREDITORID;
import static com.linkage.jz.bankruptcy.activity.Project.ZQUser.CreateZQFristApplyActivity.KEY_EDITING;
import static com.linkage.jz.bankruptcy.activity.Project.ZQUser.CreateZQFristApplyActivity.KEY_EDITING_FILE_LISTS;
import static com.linkage.jz.bankruptcy.activity.Project.ZQUser.CreateZQFristApplyActivity.KEY_TYPE;

/**
 * A login screen that offers login via email/password.
 */
public  class CreateZQBCApplyTwoActivity extends BaseCreateActivity implements OnClickListener{
    private static final String TAG = CreateZQBCApplyTwoActivity.class.getSimpleName();

    Button top_back;
    TextView top_mune1;
    private RadioGroup radioGroupArbitrate, radioGroupExecute;
    private RecyclerView uploadArbitrateRv, uploadExecuteRv, uploadOtherRv;
    private EditText editExecute,edit_bcsm;

    private ZQBaseProjectCrDecInfo mEditInfo;
    private int mType;
    private String mCreditorId;
    private String mProjectId;

    private TextView popClick;
    private SerializedZQApplyFileList mSerializedZQApplyFileLists;


    private SelectPicHelpler<TaskAtta> mArbitrateSeletor, mExecuteSeletor, mOtherSeletor;
    private final UploadImageConverter<TaskAtta> mConverter = new UploadImageConverter<TaskAtta>() {
        @Override
        public UploadImage toUploadImage(TaskAtta taskAtta) {
            UploadImage image = new UploadImage();
            image.setFilename(taskAtta.getAttachmentName());
            image.setFilesize(taskAtta.getAttachmentSize());
            image.setFilepath(taskAtta.getAttachmentDownloadAddress());
            image.setLoadUrl(taskAtta.getAttachmentPreviewAddress());
            return image;
        }

        @Override
        public TaskAtta fromUploadImage(UploadImage image) {
            TaskAtta taskAtta = new TaskAtta();
            taskAtta.setAttachmentName(image.getFilename());
            taskAtta.setAttachmentSize(image.getFilesize());
            taskAtta.setAttachmentDownloadAddress(image.getFilepath());
            taskAtta.setAttachmentPreviewAddress(image.getLoadUrl());
            return null;
        }
    };
    private final ObjValInfo onlineOVI = new ObjValInfo("1", "在线上传"),
            offlineOVI = new ObjValInfo("2", "线下提供"),
            noneOVI = new ObjValInfo("3", "无");

    /**
     *  @param context 上下文
     * @param creditorId 债权人ID
     * @param projectId 项目Id
     * @param editing //正在编辑的
     * @param type 0:管理人; 1:债权人
     */
    public static void start(Context context, String creditorId, String projectId, int type, ZQBaseProjectCrDecInfo editing) {
        Intent intent = new Intent(context, CreateZQBCApplyTwoActivity.class);
        intent.putExtra(KEY_CREDITORID, creditorId);
        intent.putExtra(KEY_PROJECTID, projectId);
        intent.putExtra(KEY_TYPE, type);
        intent.putExtra(KEY_EDITING, editing);
        context.startActivity(intent);
    }

    @Override
    public void initData() {

    }

    @Override
    public void setListener() {
        top_back.setOnClickListener(this);
        top_mune1.setOnClickListener(this);
    }

    @Override
    public void initTitle() {
        ((TextView) findViewById(R.id.top_title)).setText("上传申报文件");
    }

    @Override
    public void initView() {
        top_back = findViewById(R.id.top_back);
        top_mune1 = findViewById(R.id.top_mune1);
        editExecute = findViewById(R.id.edit_execute);
        radioGroupArbitrate = findViewById(R.id.radio_group_arbitrate);
        radioGroupExecute = findViewById(R.id.radio_group_execute);
        uploadArbitrateRv = findViewById(R.id.upload_arbitrate);
        edit_bcsm = findViewById(R.id.edit_bcsm);
        FullyGridLayoutManager manager = new FullyGridLayoutManager(this, 3, GridLayoutManager.VERTICAL, false);
        uploadArbitrateRv.setLayoutManager(manager);
        uploadExecuteRv = findViewById(R.id.upload_execute);
        FullyGridLayoutManager manager1 = new FullyGridLayoutManager(this, 3, GridLayoutManager.VERTICAL, false);
        uploadExecuteRv.setLayoutManager(manager1);
        uploadOtherRv = findViewById(R.id.upload_other);
        FullyGridLayoutManager manager2 = new FullyGridLayoutManager(this, 3, GridLayoutManager.VERTICAL, false);
        uploadOtherRv.setLayoutManager(manager2);

//        mSerializedZQApplyFileLists = getIntent().getParcelableExtra(KEY_EDITING_FILE_LISTS);

        mSerializedZQApplyFileLists = new SerializedZQApplyFileList(mEditInfo);

        popClick = findViewById(R.id.pop_click);
        /**
         * 弹窗
         */
        popClick.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                QuickPopView.show(CreateZQBCApplyTwoActivity.this);
            }
        });

        radioGroupArbitrate.setOnCheckedChangeListener(
                (group, checkedId) -> {
                    uploadArbitrateRv.setVisibility(checkedId == R.id.arbitrate1 ? View.VISIBLE : View.GONE);
                    if (mEditInfo != null) {
                        switch (checkedId) {
                            case R.id.arbitrate1:
                                mEditInfo.setHasEffectiveJudgment(onlineOVI);
                                break;
                            case R.id.arbitrate2:
                                mEditInfo.setHasEffectiveJudgment(offlineOVI);
                                break;
                            case R.id.arbitrate3:
                                mEditInfo.setHasEffectiveJudgment(noneOVI);
                                break;

                        }
                    }
                });
        radioGroupExecute.setOnCheckedChangeListener(
                (group, checkedId) -> {
                    uploadExecuteRv.setVisibility(checkedId == R.id.execute1 ? View.VISIBLE : View.GONE);
                    if (mEditInfo != null) {
                        switch (checkedId) {
                            case R.id.execute1:
                                mEditInfo.setHasApplyExecution(onlineOVI);
                                break;
                            case R.id.execute2:
                                mEditInfo.setHasApplyExecution(offlineOVI);
                                break;
                            case R.id.execute3:
                                mEditInfo.setHasApplyExecution(noneOVI);
                                break;

                        }
                    }
                    editExecute.setVisibility(checkedId == R.id.execute1 ? View.VISIBLE : View.GONE);
                });
        if (mEditInfo != null) {

            mArbitrateSeletor = new SelectPicHelpler<>(this, null, mConverter);
            mArbitrateSeletor.initView(uploadArbitrateRv);
            radioGroupArbitrate.check(R.id.arbitrate3);
            mExecuteSeletor = new SelectPicHelpler<>(this, null, mConverter);
            mExecuteSeletor.initView(uploadExecuteRv);
            radioGroupExecute.check(R.id.execute3);
            if (mEditInfo.getExecutiveDetail() != null) editExecute.setText(mEditInfo.getExecutiveDetail());
            mOtherSeletor = new SelectPicHelpler<>(this, null, mConverter);
            mOtherSeletor.initView(uploadOtherRv);
        }

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setContentView(R.layout.activity_create_zq_bc_two_apply);
        mType = getIntent().getIntExtra(KEY_TYPE, 0);
        mCreditorId = getIntent().getStringExtra(KEY_CREDITORID);
        mProjectId = getIntent().getStringExtra(KEY_PROJECTID);
        mEditInfo = getIntent().getParcelableExtra(KEY_EDITING);
        super.onCreate(savedInstanceState);
    }


    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.top_back:
                onBackPressed();
                break;
            case R.id.top_mune1:
                if (checkAmountValidate()) {
                    syncEdit();
                    submit();
//                    finish();
                }
                break;
        }
    }

    private void submit() {
        mShapeLoadingDialog.setLoadingText("提交信息中...");
        mShapeLoadingDialog.setCanceledOnTouchOutside(false);
        mShapeLoadingDialog.show();
       String edit_bcsmstr =  edit_bcsm.getText().toString();
        Network.getAPIService().supplementZQApply(getUserToken(),
                mProjectId,
                mType,
                mCreditorId,
                mEditInfo.getDeclareAmountPrincipal(),
                mEditInfo.getDeclareAmountInterest(),
                mEditInfo.getDeclareAmountInterestDetail(),
                mEditInfo.getDeclareAmountOther(),
                mEditInfo.getDeclareAmountOtherDetail(),
                mEditInfo.getDeclareAmountRegularTax(),
                mEditInfo.getDeclareAmountOverdueFine(),
                mEditInfo.getDeclareAmountTotal(),
                mEditInfo.getPreferredCreditorRights(),
                mEditInfo.getGuaranteePriority(),
                mEditInfo.getOtherPriority(),
                mEditInfo.getPreferredCreditorRightsDetail(),
                mEditInfo.getCreditorRightsNote(),
                Integer.parseInt(mEditInfo.getHasEffectiveJudgment().getValue()),
                mSerializedZQApplyFileLists.getHasEffectiveJudgmentJson(),
                Integer.parseInt(mEditInfo.getHasApplyExecution().getValue()),
                mSerializedZQApplyFileLists.getHasApplyExecutionJson(),
                mSerializedZQApplyFileLists.getHasOtherDeclarationFileJson(),
                editExecute.getText().toString(),//mEditInfo.getExecutiveDetail(),
                edit_bcsmstr)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseSubscriber<BaseResponse>() {
                    @Override
                    public void onNext(BaseResponse response) {
                        mShapeLoadingDialog.dismiss();
                        if (response.getCode() == 0) {
                            super.onNext(response);
                            Toast.makeText(CreateZQBCApplyTwoActivity.this, "已提交", Toast.LENGTH_SHORT).show();
                            finish();
                        } else {
                            Toast.makeText(CreateZQBCApplyTwoActivity.this, response.getMsg(), Toast.LENGTH_SHORT).show();
                        }
                    }

                    @Override
                    public void onCompleted() {
                        super.onCompleted();
                    }

                    @Override
                    public void onError(Throwable e) {
                        mShapeLoadingDialog.dismiss();
                        Toast.makeText(CreateZQBCApplyTwoActivity.this, "提交失败", Toast.LENGTH_SHORT).show();
                        super.onError(e);
                    }
                });
    }

    private void syncEdit() {
        mEditInfo.setExecutiveDetail(editExecute.getText().toString());
//        mEditInfo.setHasEffectiveJudgmentJson(mArbitrateSeletor.getUploadedImagesJson());
//        mEditInfo.setHasApplyExecutionJson(mExecuteSeletor.getUploadedImagesJson());
//        mEditInfo.setHasOtherDeclarationFileJson(mOtherSeletor.getUploadedImagesJson());

        try {
            JSONArray jsonArray = new JSONArray();
            for (int i = 0; i < mArbitrateSeletor.getUploadedImages().size(); i++) {
                if (TextUtils.equals(mArbitrateSeletor.getUploadedImages().get(i).getFilename(), NAME_ADD)) {
                    continue;
                }
                JSONObject jsonObject = new JSONObject();

                UploadImage image = mArbitrateSeletor.getUploadedImages().get(i);
//                jsonObject.put("attachmentName", urlList1.get(i).getFilename());
                jsonObject.putOpt("attachmentName", "相关附件" + (i + 1) + ".jpg");
                jsonObject.put("attachmentDownloadAddress", image.getFilepath());
                jsonObject.put("attachmentSize", image.getFilesize());
                jsonArray.put(jsonObject);
            }

            mSerializedZQApplyFileLists.setHasEffectiveJudgmentJson(jsonArray.toString());
//        }
//        if (mExecuteSeletor != null && mSerializedZQApplyFileLists != null) {

            JSONArray jsonArray2 = new JSONArray();
            for (int i = 0; i < mExecuteSeletor.getUploadedImages().size(); i++) {
                if (TextUtils.equals(mExecuteSeletor.getUploadedImages().get(i).getFilename(), NAME_ADD)) {
                    continue;
                }
                JSONObject jsonObject = new JSONObject();
                UploadImage image = mExecuteSeletor.getUploadedImages().get(i);
//                jsonObject.put("attachmentName", urlList1.get(i).getFilename());
                jsonObject.putOpt("attachmentName", "相关附件" + (i + 1) + ".jpg");
                jsonObject.put("attachmentDownloadAddress", image.getFilepath());
                jsonObject.put("attachmentSize", image.getFilesize());
                jsonArray2.put(jsonObject);
            }

            mSerializedZQApplyFileLists.setHasApplyExecutionJson(jsonArray2.toString());
//        }
//        if (mOtherSeletor != null && mSerializedZQApplyFileLists != null) {

            JSONArray jsonArray3 = new JSONArray();
            for (int i = 0; i < mOtherSeletor.getUploadedImages().size(); i++) {
                JSONObject jsonObject = new JSONObject();
                UploadImage image = mOtherSeletor.getUploadedImages().get(i);
//                jsonObject.put("attachmentName", urlList1.get(i).getFilename());
                jsonObject.putOpt("attachmentName", "相关附件" + (i + 1) + ".jpg");
                jsonObject.put("attachmentDownloadAddress", image.getFilepath());
                jsonObject.put("attachmentSize", image.getFilesize());
                jsonArray3.put(jsonObject);
            }

            mSerializedZQApplyFileLists.setHasOtherDeclarationFileJson(jsonArray3.toString());
//        }
        }catch (Exception ex){
            ex.printStackTrace();
        }

    }

    private boolean checkAmountValidate() {
        if (radioGroupArbitrate.getCheckedRadioButtonId() == R.id.arbitrate1
                && mArbitrateSeletor.getUploadedImages().size()==1) {
            new android.support.v7.app.AlertDialog.Builder(this)
                    .setTitle("提示")
                    .setMessage("请上传生效判决/裁决，或选择其他选项")
                    .setCancelable(false)
                    .setPositiveButton("我知道了", null)
                    .show();
            return false;
        }
        if (radioGroupExecute.getCheckedRadioButtonId() == R.id.execute1
                && mExecuteSeletor.getUploadedImages().size()==1) {
            new android.support.v7.app.AlertDialog.Builder(this)
                    .setTitle("提示")
                    .setMessage("请上传申请执行文件，或选择其他选项")
                    .setCancelable(false)
                    .setPositiveButton("我知道了", null)
                    .show();
            return false;
        }
        return true;
    }
}

